﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Net;
using System.Net.Http;
using System.IO;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;
using CCWin;
using CCWin.SkinControl;

namespace Mes.质检管理.InspectionModel
{
    public partial class InspectionShow : Form
    {
        private const string API_URL = "/api/Inspection/GetInspection";

        public InspectionShow()
        {
            InitializeComponent();
            InitializeForm();
        }

        /// <summary>
        /// 窗体初始化：绑定按钮事件，加载数据
        /// </summary>
        private void InitializeForm()
        {
            // 绑定按钮事件
            btnRefresh.Click += BtnRefresh_Click;
            btnAdd.Click += BtnAdd_Click;
            btnClose.Click += BtnClose_Click;

            // 初始化DataGridView列
            InitializeDataGridView();

            // 加载数据
            LoadInspectionData();
        }

        /// <summary>
        /// 初始化DataGridView列
        /// </summary>
        private void InitializeDataGridView()
        {
            // 清空现有列
            dataGridView1.Columns.Clear();

            // 添加列
            dataGridView1.Columns.Add("Id", "序号");
            dataGridView1.Columns.Add("InspectionItemNo", "项目编号");
            dataGridView1.Columns.Add("InspectionItemName", "项目名称");
            dataGridView1.Columns.Add("InspectionMethod", "质检方法");
            dataGridView1.Columns.Add("InspectionTool", "质检工具");
            dataGridView1.Columns.Add("InspectionType", "质检类型");
            dataGridView1.Columns.Add("StandardValue", "标准值");
            dataGridView1.Columns.Add("Remarks", "备注");
            dataGridView1.Columns.Add("Action", "操作");

            // 设置列宽
            dataGridView1.Columns["Id"].Width = 60;
            dataGridView1.Columns["InspectionItemNo"].Width = 100;
            dataGridView1.Columns["InspectionItemName"].Width = 120;
            dataGridView1.Columns["InspectionMethod"].Width = 100;
            dataGridView1.Columns["InspectionTool"].Width = 100;
            dataGridView1.Columns["InspectionType"].Width = 80;
            dataGridView1.Columns["StandardValue"].Width = 100;
            dataGridView1.Columns["Remarks"].Width = 150;
            dataGridView1.Columns["Action"].Width = 80;

            // 设置样式
            dataGridView1.EnableHeadersVisualStyles = false;
            dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(64, 64, 64);
            dataGridView1.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
            dataGridView1.ColumnHeadersDefaultCellStyle.Font = new Font("Microsoft YaHei UI", 9F, FontStyle.Bold);
        }

        /// <summary>
        /// 刷新按钮点击事件
        /// </summary>
        private void BtnRefresh_Click(object sender, EventArgs e)
        {
            LoadInspectionData();
        }

        /// <summary>
        /// 新增按钮点击事件
        /// </summary>
        private void BtnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                // 创建新增窗体
                var inspectionAddForm = new InspectionAdd();
                
                // 显示为模态对话框
                if (inspectionAddForm.ShowDialog() == DialogResult.OK)
                {
                    // 如果新增成功，刷新列表
                    LoadInspectionData();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开新增页面时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 关闭按钮点击事件
        /// </summary>
        private void BtnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 从后端API加载质检项目数据
        /// </summary>
        private void LoadInspectionData()
        {
            try
            {
                // 显示加载状态
                Cursor = Cursors.WaitCursor;
                btnRefresh.Enabled = false;

                // 清空现有数据
                dataGridView1.Rows.Clear();

                // 调用API获取数据
                var inspectionList = GetInspectionDataFromAPI();

                if (inspectionList != null && inspectionList.Count > 0)
                {
                    // 填充DataGridView
                    PopulateDataGridView(inspectionList);
                }
                else
                {
                    MessageBox.Show("未找到质检项目数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复状态
                Cursor = Cursors.Default;
                btnRefresh.Enabled = true;
            }
        }

        /// <summary>
        /// 调用后端API获取质检项目数据
        /// </summary>
        /// <returns>质检项目列表</returns>
        private List<InspectionItem> GetInspectionDataFromAPI()
        {
            try
            {
                // 使用HttpClient直接调用接口
                using (var httpClient = new HttpClient())
                {
                    // 设置超时时间
                    httpClient.Timeout = TimeSpan.FromSeconds(30);
                    
                    // 发送GET请求
                    var response = httpClient.GetAsync(HttpClientHelper.GetApiUrl("/api/Inspection/GetInspection")).Result;
                    
                    // 检查响应状态
                    if (response.IsSuccessStatusCode)
                    {
                        // 读取响应内容
                        string jsonResponse = response.Content.ReadAsStringAsync().Result;
                        return ParseInspectionData(jsonResponse);
                    }
                    else
                    {
                        // 处理错误响应
                        string errorContent = response.Content.ReadAsStringAsync().Result;
                        throw new Exception($"API调用失败: {response.StatusCode} - {errorContent}");
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"获取数据时发生错误：{ex.Message}");
            }
        }

        /// <summary>
        /// 解析API返回的JSON数据
        /// </summary>
        /// <param name="jsonData">JSON字符串</param>
        /// <returns>质检项目列表</returns>
        private List<InspectionItem> ParseInspectionData(string jsonData)
        {
            try
            {
                // 如果API返回的是包装在Result对象中的数据
                if (jsonData.Contains("\"result\"") || jsonData.Contains("\"data\""))
                {
                    // 尝试解析包装的响应
                    var response = JsonConvert.DeserializeObject<ApiResponse<List<InspectionItem>>>(jsonData);
                    return response?.Result ?? response?.Data ?? new List<InspectionItem>();
                }
                else
                {
                    // 直接解析数组
                    return JsonConvert.DeserializeObject<List<InspectionItem>>(jsonData) ?? new List<InspectionItem>();
                }
            }
            catch (JsonException ex)
            {
                throw new Exception($"JSON解析错误：{ex.Message}\n原始数据：{jsonData}");
            }
        }

        /// <summary>
        /// 将质检项目数据填充到DataGridView中
        /// </summary>
        /// <param name="inspectionList">质检项目列表</param>
        private void PopulateDataGridView(List<InspectionItem> inspectionList)
        {
            int sequenceNumber = 1;
            foreach (var item in inspectionList)
            {
                int rowIndex = dataGridView1.Rows.Add();
                var row = dataGridView1.Rows[rowIndex];

                row.Cells["Id"].Value = sequenceNumber.ToString();
                row.Cells["InspectionItemNo"].Value = item.InspectionItemNo ?? "";
                row.Cells["InspectionItemName"].Value = item.InspectionItemName ?? "";
                row.Cells["InspectionMethod"].Value = item.InspectionMethod ?? "";
                row.Cells["InspectionTool"].Value = item.InspectionTool ?? "";
                row.Cells["InspectionType"].Value = GetInspectionTypeText(item.InspectionType);
                row.Cells["StandardValue"].Value = item.StandardValue ?? "";
                row.Cells["Remarks"].Value = item.Remarks ?? "";
                row.Cells["Action"].Value = "删除";

                // 将原始数据存储在Tag中，用于删除操作
                row.Tag = item;

                sequenceNumber++;
            }
        }

        /// <summary>
        /// DataGridView单元格点击事件处理
        /// </summary>
        private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                // 检查是否点击的是操作列（最后一列）
                if (e.ColumnIndex == dataGridView1.Columns["Action"].Index)
                {
                    // 获取对应的质检项目数据
                    var inspectionItem = dataGridView1.Rows[e.RowIndex].Tag as InspectionItem;
                    if (inspectionItem != null)
                    {
                        // 确认删除
                        if (MessageBox.Show($"确定要删除质检项目 '{inspectionItem.InspectionItemName}' 吗？", 
                            "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            // 执行删除操作
                            DeleteInspectionItem(inspectionItem);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 删除质检项目
        /// </summary>
        /// <param name="inspectionItem">要删除的质检项目</param>
        private void DeleteInspectionItem(InspectionItem inspectionItem)
        {
            try
            {
                // 显示删除状态
                Cursor = Cursors.WaitCursor;

                // 调用删除API
                bool success = DeleteInspectionFromAPI(inspectionItem.Id ?? 0);

                if (success)
                {
                    MessageBox.Show("删除成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    // 刷新数据
                    LoadInspectionData();
                }
                else
                {
                    MessageBox.Show("删除失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除过程中发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复状态
                Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// 调用后端API删除质检项目
        /// </summary>
        /// <param name="id">质检项目ID</param>
        /// <returns>是否删除成功</returns>
        private bool DeleteInspectionFromAPI(int id)
        {
            try
            {
                // 构建删除请求的JSON数据
                string jsonData = $"{{\"id\":{id}}}";
                
                // 使用HttpClient直接调用接口
                using (var httpClient = new HttpClient())
                {
                    // 设置超时时间
                    httpClient.Timeout = TimeSpan.FromSeconds(30);
                    
                    // 创建请求内容
                    var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                    
                    // 发送POST请求
                    var response = httpClient.PostAsync(HttpClientHelper.GetApiUrl("/api/Inspection/DeleteInspection"), content).Result;
                    
                    // 检查响应状态
                    return response.IsSuccessStatusCode;
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"删除数据时发生错误：{ex.Message}");
            }
        }

        /// <summary>
        /// 获取质检类型的中文显示文本
        /// </summary>
        /// <param name="inspectionType">质检类型值</param>
        /// <returns>中文显示文本</returns>
        private string GetInspectionTypeText(string inspectionType)
        {
            if (string.IsNullOrEmpty(inspectionType))
                return "未知";

            switch (inspectionType.Trim())
            {
                case "1":
                    return "数值";
                case "2":
                    return "外观";
                case "3":
                    return "质量";
                default:
                    return inspectionType;
            }
        }
    }

    /// <summary>
    /// 质检项目数据模型
    /// </summary>
    public class InspectionItem
    {
        public int? Id { get; set; }
        public string InspectionItemNo { get; set; }
        public string InspectionItemName { get; set; }
        public string InspectionMethod { get; set; }
        public string InspectionTool { get; set; }
        public string InspectionType { get; set; }
        public string StandardValue { get; set; }
        public string Remarks { get; set; }
    }

    /// <summary>
    /// API响应包装类
    /// </summary>
    public class ApiResponse<T>
    {
        public T Result { get; set; }
        public T Data { get; set; }
        public bool Success { get; set; }
        public string Message { get; set; }
    }
}
